// pages/me/basic/basic.js
const https = require('../../../utils/https.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    basic: {},
    groupList: [],
    ocr_id: 0,
    pickerArrIndex: -1
  },
  bindPickerChange(e) {
    this.setData({
      pickerArrIndex: e.detail.value
    })
    this.data.basic.group_id = this.data.groupList[e.detail.value].id
  },
  back() {
    wx.navigateBack({
      delta: 1
    })
  },
  tapToNext(e) {
    wx.navigateTo({
      url: '../basic-detail/basic-detail'
    })
  },
  del() {
    const that = this
    https.post('/api/ocr/del', this.data.basic).then((res) => {
      if (res.code == 0) {
        that.tapToNext()
      return
      }
      if (res.msg) {
        wx.showToast({
          title: res.msg,
          icon: 'none', // error loading none
          mask: true, // 是否显示透明蒙层，防止触摸穿透
          duration: 1000
        })
      }
    })
  },
  save() {
    const that = this
    https.post('/api/ocr/edit-basic', this.data.basic).then((res) => {
      if (res.code == 0) {
        setTimeout(() => {
          wx.navigateTo({
            url: '../basic-detail/basic-detail?id='+that.data.ocr_id
          })
        }, 1500)
      }
      if (res.msg) {
        wx.showToast({
          title: res.msg,
          icon: 'none', // error loading none
          mask: true, // 是否显示透明蒙层，防止触摸穿透
          duration: 1000
        })
      }
    })
  },
  getData() {
    const that = this
    https.post('/api/ocr/info', {id: this.data.ocr_id}).then((res) => {
      if (res.code == 0) {
        this.setData({
          basic: res.data.basic
        })
        that.getDataGroup()
        return
      }
      wx.showToast({
        title: '数据获取失败！',
        icon: 'none', // error loading none
        mask: true, // 是否显示透明蒙层，防止触摸穿透
        duration: 1000
      })
    })
  },
  getDataGroup() {
    const that = this
    var pickerArrIndex = -1
    https.get('/api/group', {}).then((res) => {
      if (res.code == 0) {
        res.data.data.forEach((item, index) => {
          if (item.id == that.data.basic.group_id) {
            pickerArrIndex = index
          }
        })
        this.setData({
          groupList: res.data.data,
          pickerArrIndex: pickerArrIndex
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */ 
  onLoad: function (options) {
    if (!options.id && wx.getAccountInfoSync().miniProgram.envVersion == 'develop') {
      options.id = 13
    }
    
    this.setData({
      ocr_id: options.id
    })
    this.getData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})